package org.lc.httpcollector.tool

import com.alibaba.fastjson2.JSON
import org.lc.httpcollector.afterSaveFile
import org.lc.httpcollector.mapPathName
import org.lc.httpcollector.mapServerName
import org.lc.httpcollector.model.Response
import org.lc.httpcollector.model.Server
import java.io.File
import kotlin.io.path.Path
import kotlin.io.path.createDirectories

object FileUtil {
    /**
     * 保存默认格式文件
     */
    fun saveDefaultFile(server: Server, url: String, response: Response) {
        if (url.isEmpty() || !url.startsWith('/')) throw IllegalArgumentException("url format error: $url")
        val lastSeparatorIndex = url.lastIndexOfOrNull('/') ?: throw IllegalArgumentException("url format error $url")

        val dirPath = mapPathName(url.substring(0, lastSeparatorIndex).replace('/', File.separatorChar))
        val fileBaseName = mapPathName(url.substring(lastSeparatorIndex + 1))
        val basePath = mapServerName(server) + dirPath

        Path(basePath).createDirectories()
        File(basePath, "$fileBaseName.GET").writeText(response.body ?: "")
        File(basePath, "$fileBaseName.GET.HEADER").bufferedWriter().use {
            response.headers.forEach { (k, v) -> it.write("$k=$v${System.lineSeparator()}") }
        }
        afterSaveFile(server, url, response)
    }

    /**
     * 保存dmtf风格的文件
     */
    fun saveDmtfFile(server: Server, url: String, response: Response) {
        if (url.isEmpty() || !url.startsWith('/')) throw IllegalArgumentException("url format error: $url")

        val basePath = mapServerName(server) + mapPathName(url.replace('/', File.separatorChar))
        Path(basePath).createDirectories()
        File(basePath, "index.json").writeText(response.body ?: "")
        val headerMap = mapOf("GET" to response.headers)
        File(basePath, "headers.json").writeText(JSON.toJSONString(headerMap))
    }
}